#include <algorithm>
#include "light_system.h"
#include "main_game_shell.h"
#include "automessage.h"
#include "ltservershell.h"
#include "msgids.h"
struct sort_by_position {
    sort_by_position(const LTVector& pos) : m_pos(pos) {
    }
    const LTVector& m_pos ;
    bool operator()(const shader_light& lhs,
                  const shader_light& rhs) const {
        LTVector l(lhs.Position[0], lhs.Position[1], lhs.Position[2]) ;
        LTVector r(rhs.Position[0], rhs.Position[1], rhs.Position[2]) ;
        float a = l.DistSqr(m_pos) ;
        float b = r.DistSqr(m_pos) ;
        return a < b ;
        
    }
} ;
light_system::light_system(game_logic_shell* shell) :
    m_shell(shell) 
{
}

void light_system::send_light_to_client(HCLIENT hclient, const LTVector& pos) {
    if(m_lights.empty()) return ;
    if(m_lights.size() <= 4) {
        send_top_lights(hclient, m_lights.size() ) ;
    } else {
        std::sort(m_lights.begin(), m_lights.end(), sort_by_position(pos)) ;
        send_top_lights(hclient, 4) ;
    }
}

void light_system::send_top_lights(HCLIENT hclient, size_t num) {
    CAutoMessage msg ;
    msg.Writeuint8(MSG_LIGHT_INFO_MESSAGE) ;
    msg.Writeuint32(num) ;
    for(size_t i = 0 ; i < num ; i++)
        msg.WriteData(&(m_lights[i]), sizeof(shader_light) * 8) ;
    g_pLTServer->SendToClient(msg.Read(), hclient, NULL) ;
    
}


